package com.sharemarking.platform.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sharemarking.platform.service.ValidateCodeService;
import com.sharemarking.system.entity.Role;
import com.sharemarking.system.entity.User;
import com.sharemarking.system.mapper.RoleMapper;
import com.sharemarking.system.mapper.UserMapper;

@Controller
@RequestMapping("password")
public class PasswordController {
	
	@Autowired
	private ValidateCodeService vcs;
	
	@Autowired
	private CacheManager cm;
	
//	@Autowired
//	private KafkaService ks;
	
//	@Autowired
//	KafkaProperties kp;
//	
	@Autowired
	PasswordEncoder pe;
	
	@Autowired
	private UserMapper um;
	
	@Autowired
	private RoleMapper rm;
	
	private final String PASSWORD_IMAGE_VALIDATECODE="PASSWORD_IMAGE_VALIDATECODE";
	private final String PASSWORD_SMS_VALIDATECODE="PASSWORD_SMS_VALIDATECODE";
	
	@GetMapping("index")
	public String index(Model model) {
		model.addAttribute("reqId", UUID.randomUUID().toString());
		model.addAttribute("ts", System.currentTimeMillis());
		return "password/step1";
	}
	
	@PostMapping("index")
	public String indexPost(String reqId,String mobile,String validateCode,String password,Model model) {
		if(reqId==null)return "redirect:index";
		ValueWrapper v=cm.getCache(PASSWORD_SMS_VALIDATECODE).get(mobile);
		if(v!=null && v.get().equals(validateCode)) {
			if(StringUtils.isEmpty(password)) {
				model.addAttribute("reqId", reqId);
				model.addAttribute("mobile", mobile);
				model.addAttribute("validateCode", validateCode);
				return "password/step2";
			} else {
				cm.getCache(PASSWORD_SMS_VALIDATECODE).evict(mobile);
				User user=um.getByMobile(mobile);
				List<Integer> roleIdList=um.getRoleIdsByUserId(user.getId());
				boolean isEnterpriceUser=false;
				for(int i:roleIdList) {
					Role role=rm.get(i);
					if(role.getName().equals("企业用户"))isEnterpriceUser=true;
				}
				if(isEnterpriceUser) {
					user.setPassword(pe.encode(password));
					um.updatePassword(user);
					return "password/success";
				}
			}
		}
		return "redirect:index";
	}
	
	@GetMapping("validateCode/{reqId}")
	public void registerValidateCode(HttpServletResponse response,@PathVariable("reqId")String reqId) throws IOException{
		Object[] validateCode=vcs.createImage();
		Cache cache=cm.getCache(PASSWORD_IMAGE_VALIDATECODE);
		cache.put(reqId, validateCode[0]);
		response.setContentType("image/png");
		ImageIO.write((BufferedImage)validateCode[1], "png", response.getOutputStream());
		response.getOutputStream().flush();
	}
	
	
//	@PostMapping("smsCode/{reqId}")
//	@ResponseBody
//	public Map<String,Object> smsCode(String validateCode,String mobile,@PathVariable("reqId")String reqId) {
//		Cache cache=cm.getCache(PASSWORD_IMAGE_VALIDATECODE);
//		ValueWrapper vw=cache.get(reqId);
//		String registerValidateCode=vw==null?null:(String)vw.get();
//		Map<String,Object> map=new HashMap<String,Object>(2);
//		if(validateCode==null||!validateCode.equalsIgnoreCase(registerValidateCode)) {
//			map.put("success", 0);
//			map.put("msg", "图形验证码错误");
//			return map;
//		}else {
//			ValueWrapper v=cm.getCache(PASSWORD_SMS_VALIDATECODE).get(mobile);
//			if(v!=null) {
//				map.put("success", 0);
//				map.put("msg", "请勿重复发送短信");
//				return map;
//			}
//			map.put("success", 1);
//			map.put("msg", "短信已发送");
//			int rand=new Random().nextInt(1000000);
//			String code=String.format("%06d", rand);
//			cm.getCache(PASSWORD_SMS_VALIDATECODE).put(mobile,code);
//			Messeage mes=new Messeage(MesseageType.REGISTER, mobile, "{\"code\":\""+code+"\"}");
//			ks.publishAvroObj(kp.getTopic().getSendMesseage(), mes);
//			return map;
//		}
//	}
}
